from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .. models import Types,Goods

from django.contrib.auth.decorators import permission_required
from django.db.models import Q
# Create your views here.



# 商品添加网页
@permission_required('myadmin.insert_goods',raise_exception = True)
def goodsadd(request):
	from . typeviews import GetTypesAll
	tlist = GetTypesAll()

	context = {'tlist':tlist}
	return render(request,'admin/goods/add.html',context)
	# return HttpResponse('goodsadd')

# 执行商品添加
@permission_required('myadmin.insert_goods',raise_exception = True)
def goodsinsert(request):
	# 判断图片是否上传
	if not request.FILES.get('pic',None):
		return HttpResponse('<script>alert("请选择上传的商品图片");location.href="/admin/goods/add"</script>')
	try:
		obj = Goods()
		obj.typeid = Types.objects.get(id=request.POST['typeid'])
		obj.title = request.POST['title']
		obj.price = request.POST['price']
		obj.storage = request.POST['storage']
		obj.info = request.POST['info']
		obj.pic = uploads(request)
		obj.save()
		return HttpResponse('<script>alert("添加成功");location.href="/admin/goods/list"</script>')
	except:
		return HttpResponse('<script>alert("添加失败");location.href="/admin/goods/add"</script>')


# 商品列表
@permission_required('myadmin.show_goods',raise_exception = True)
def goodslist(request):
	# 清除ajax上传的文件
	import os
	for i in os.listdir('.'+'/static/pics/tmp'):
		os.remove('.'+'/static/pics/tmp/'+i)

	# 商品列表
	types = request.GET.get('types',None)
	keywords = request.GET.get('keywords')
	# print(types,keywords)
	data = Types.objects.none()
	if types:
		if types == 'all':
			data = Goods.objects.filter(Q(id__contains=keywords)|Q(title__contains=keywords)|Q(price__contains=keywords)|Q(storage__contains=keywords)|Q(num__contains=keywords)|Q(clicknum__contains=keywords)|Q(addtime__contains=keywords))
			# 商品状态
			if keywords in '新品':
				data = data | Goods.objects.filter(status__contains='1')
			elif keywords in '热卖':
				data = data | Goods.objects.filter(status__contains='2')
			elif keywords in '下架':
				data = data | Goods.objects.filter(status__contains='3')
			
			# 所属分类
			tobj = Types.objects.all()
			dict_typeid = {}
			for v in tobj:
				dict_typeid.setdefault(v.name,v.id)

			list1=[]
			for k in dict_typeid:
				if keywords in k:
					list1.append(k)
			# list1 ['服装', '男装', '女装']
			for i in list1:
				#  通过列表获取 type的is
				ids = dict_typeid.get(i)
				if ids:
					data = data | Goods.objects.filter(typeid__id=str(ids))
	
		elif types == 'id':
			data = Goods.objects.filter(id__contains=keywords)
		elif types == 'title':
			data = Goods.objects.filter(title__contains=keywords)
		elif types == 'price':
			data = Goods.objects.filter(price__contains=keywords)
		elif types == 'num':
			data = Goods.objects.filter(num__contains=keywords)
		elif types == 'clicknum':
			data = Goods.objects.filter(clicknum__contains=keywords)
		elif types == 'addtime':
			data = Goods.objects.filter(addtime__contains=keywords)
		elif types == 'storage':
			data = Goods.objects.filter(storage__contains=keywords)
		elif types == 'status':
			if keywords in '新品':
				data = data | Goods.objects.filter(status__contains='1')
			elif keywords in '热卖':
				data = data | Goods.objects.filter(status__contains='2')
			elif keywords in '下架':
				data = data | Goods.objects.filter(status__contains='3')
		elif types == 'typeid':
			# 获取商品分类的id和name的键值对
			tobj = Types.objects.all()
			dict_typeid = {}
			for v in tobj:
				dict_typeid.setdefault(v.name,v.id)
			# {'服装': 3, '电视': 19, '音乐类': 10, 
			# '家电': 1, '冰箱': 18, '洗衣机': 9, '流行': 
			# 20, '男装': 5, '女装': 6}
			# print(dict_typeid)
			# dict_typeid.get(keywords,'0#06a')
			
			# 通过keywords 得出 id
			list1=[]
			for k in dict_typeid:
				if keywords in k:
					list1.append(k)
			# list1 ['服装', '男装', '女装']
			for i in list1:
				#  通过列表获取 type的is
				ids = dict_typeid.get(i)
				if ids:
					data = data | Goods.objects.filter(typeid__id=str(ids))

	else:
		data = Goods.objects.all()


	# data = Goods.objects.all()

	# 数据分页
	from django.core.paginator import Paginator
	# 实例化分页类 参数1-参数的数据，参数2-每页显示的数据
	paginator = Paginator(data,5)
	# 当前页码
	p = int(request.GET.get('p',1))
	# 根据当前页码获取当前页码应该显示的数据
	tlist = paginator.page(p)
	# 获取当前页的页码数
	num = paginator.page_range
	
	context = {'glist':tlist,'pagenum':num}
	return render(request,'admin/goods/list.html',context)


# 商品状态更新
def goodsstatus(request):
	gid = request.GET['gid']
	obj = Goods.objects.get(id=gid)
	obj.status = int(request.GET['status'])
	obj.save()
	return HttpResponse('goodsstatus')


# 商品编辑
@permission_required('myadmin.edit_goods',raise_exception = True)
def goodsedit(request,gid):

	obj = Goods.objects.get(id=gid)
	tlist = Types.objects.all()
	context = {'ginfo':obj,'tlist':tlist}

	return render(request,'admin/goods/edit.html',context)


# 执行更新
@permission_required('myadmin.edit_goods',raise_exception = True)
def goodsupdate(request):
	try:
		# 获取要执行更新的数据项
		obj = Goods.objects.get(id=request.POST['gid'])
		obj.typeid = Types.objects.get(id=request.POST['typeid'])
		print(request.POST['typeid'])
		obj.title = request.POST['title']
		obj.price = request.POST['price']
		obj.storage = int(request.POST['storage'])
		obj.info = request.POST['info']
		
		# 上传了图片
		if request.FILES.get('pic',None):
			# 删除原图片
			import os
			os.remove('.'+obj.pic)
			# 上传新图片
			obj.pic = uploads(request)
			
		obj.save()
		return HttpResponse('<script>alert("修改成功");location.href="/admin/goods/list"</script>')
	except:
		return HttpResponse('<script>alert("修改失败");location.href="/admin/goods/edit/'+str(obj.id)+'"</script>')

@permission_required('myadmin.del_goods',raise_exception = True)
def goodsdel(request):
	try:
		gid = request.GET['gid']
		obj = Goods.objects.get(id = gid)
		# 删除商品商品图片
		import os
		os.remove('.'+str(obj.pic))
		obj.delete()

		return JsonResponse({'status':3,'msg':'删除成功'})
	except:
		return JsonResponse({'status':1,'msg':'删除失败'})






def uploads(request):
	myfile = request.FILES.get('pic',None)
	#判断是否有文件上传
	if not myfile:
		# 返回默认头像
		return '/static/pics/default/default.ico'

	# 执行文件上传
	import time,random
	# 头像名称 时间戳+随机数+.+后缀名
	filename = str(time.time())+str(random.randrange(10000,99999))
	# 获取当前文件后缀名
	hzm = myfile.name.split('.').pop()
	# 当前允许上传的后缀名
	arr = ['ico','jpg','jpeg','gif','bmp','png']
	if hzm not in arr:
		return False

	# 打开文件
	file = open('./static/pics/'+filename+'.'+hzm,'wb+')
	# 分块写入文件
	for chunk in myfile.chunks():
		file.write(chunk)
	# 关闭文件
	file.close()

	# 返回文件的url路径
	return '/static/pics/'+filename+'.'+hzm